package cn.edu.tju.cas.dao.impl;

import cn.edu.tju.cas.dao.BaseDao;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;


public abstract class BaseDaoImpl<T extends Serializable> extends HibernateDaoSupport implements BaseDao<T> {

    private Class<T> clazz;

    protected void setClass(final Class<T> clazz){
        this.clazz = clazz;
    }

    public T findById(final int id){
        return getHibernateTemplate().get(clazz, id);
    }

    public List<T> findAll(){
        return (List<T>)getHibernateTemplate().find("from " + clazz.getName());
    }

    public Integer save(final T entity){
        getHibernateTemplate().getSessionFactory().getCurrentSession().flush();
        return (Integer) getHibernateTemplate().save(entity);
    }

    public T update(T entity) {
        getHibernateTemplate().update(entity);
        return entity;
    }

    public void delete(final T entity) {
        getHibernateTemplate().delete(entity);
    }

    public void deleteById(final int entityId) {
        T t = findById(entityId);
        if(t != null)
            delete(t);
    }

    public T getOneFromList(List list) {
        if(list.size() == 0){
            return null;
        }

        return (T)list.get(0);
    }

    @Autowired
    public void setSessionFactory0(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }
}